import React, { useState, useRef, useEffect } from "react";
import "./index.css";

interface CoderProps {
  example: {
    id: string;
    title: string;
    css: string;
    html: string;
  };
  index: number;
}

// 代码编辑器和预览组件
const Coder: React.FC<CoderProps> = ({ example, index }) => {
  const [customCSS, setCustomCSS] = useState(example.css);
  const [htmlCode, setHtmlCode] = useState(example.html);
  const styleRef = useRef<HTMLStyleElement | null>(null);
  const styleId = `example-style-${index}`;

  // 实时更新样式 - 为每个示例添加独立的CSS作用域
  useEffect(() => {
    // 移除旧的样式元素
    const oldStyle = document.getElementById(styleId);
    if (oldStyle) {
      oldStyle.remove();
    }

    // 为CSS添加唯一作用域，确保只应用到当前示例
    const scopedCSS = customCSS
      .split("\n")
      .map((line) => {
        // 为选择器添加作用域前缀
        if (
          line.trim() &&
          !line.trim().startsWith("/*") &&
          !line.trim().startsWith("}") &&
          !line.trim().startsWith("{")
        ) {
          // 处理选择器行
          if (line.includes("{")) {
            const parts = line.split("{");
            const selectors = parts[0].trim();
            const rest = parts.slice(1).join("{");
            // 为每个选择器添加作用域
            const scopedSelectors = selectors
              .split(",")
              .map((selector) => `.grid-example-${index} ${selector.trim()}`)
              .join(", ");
            return `${scopedSelectors} {${rest}`;
          }
        }
        return line;
      })
      .join("\n");

    // 创建新的样式元素
    const style = document.createElement("style");
    style.id = styleId;
    style.textContent = scopedCSS;
    document.head.appendChild(style);
    styleRef.current = style;

    // 清理函数
    return () => {
      if (styleRef.current) {
        styleRef.current.remove();
      }
    };
  }, [customCSS, styleId, index]);

  // 生成网格项 - 使用当前的HTML代码状态
  const renderGridItems = () => {
    return <div dangerouslySetInnerHTML={{ __html: htmlCode }} />;
  };

  return (
    <div className="example-block">
      <h2>{example.title}</h2>
      <div className="content-container">
        {/* 左侧 - 代码编辑区 */}
        <div className="code-section">
          <h3>CSS代码</h3>
          <textarea
            className="code-editor"
            value={customCSS}
            onChange={(e) => setCustomCSS(e.target.value)}
            rows={10}
            spellCheck={false}
          />

          <h3>HTML代码</h3>
          <textarea
            className="code-editor html-editor"
            value={htmlCode}
            onChange={(e) => setHtmlCode(e.target.value)}
            rows={10}
            spellCheck={false}
          />
        </div>

        {/* 右侧 - 预览区 */}

        <div className="preview-section">
          <h3>预览</h3>
          <div className={`grid-preview grid-example-${index}`}>
            {renderGridItems()}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Coder;
